// Created: Dec 13, 2014
//
// Author: wjinwen.1988@gmail.com

#include "chi/net/channel.h"

#include <assert.h>

#include <event.h>
#include <glog/logging.h>

#include "chi/net/event_loop.h"

namespace chi {
namespace net {

const int Channel::kNoneEvent = 0;
const int Channel::kReadEvent = EV_READ | EV_PERSIST;
const int Channel::kWriteEvent = EV_WRITE;

Channel::Channel(EventLoop* loop, const int fd) 
    : loop_(loop),
      fd_(fd),
      events_(0),
      revents_(0) { 
}

Channel::~Channel() {
}

void Channel::HandleEvent() {
  if (revents_ & kReadEvent) {
    read_cb_();
  } else if (revents_ & kWriteEvent) {
    write_cb_();
  } else {
    close_cb_();
    LOG(ERROR) << "Unknown revents: " << revents_;
  }
}

void Channel::EnableReading() {
  events_ |= kReadEvent;
  Update();
}

void Channel::EnableWriting() {
  events_ |= kWriteEvent;
  Update();
}

void Channel::DisableWriting() {
  events_ &= ~kWriteEvent; 
  Update();
}

void Channel::DisableAll() {
  events_ = kNoneEvent;
  Update();
}

bool Channel::IsWriting() const { return events_ & kWriteEvent; }

void Channel::Update() { loop_->UpdateChannel(this); }

} 
}
